var api = require('../../api.js');
var util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    lng:"",
    lat:"",
    markers:[],
    showList:true,
    list:[],
    maptop: "100rpx",
    sectionlistTrue: false,
    maptype:"l",
    historylist:[],
    startPoint:"",//当前地址名称
    startlng:"",
    startlat:""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var addresslist = [];
    var addressHistory = wx.getStorageSync("addressHistory") == "" ? [] : wx.getStorageSync("addressHistory");
    for (let v in addressHistory) {
      addresslist[v] = JSON.parse(addressHistory[v]);
    }
    this.setData({ historylist: addresslist })
    var to_addressHistory = wx.getStorageSync("to_addressHistory") == "" ? [] : wx.getStorageSync("to_addressHistory");
    var to_addresslist = [];
    for (let v in to_addressHistory) {
      to_addresslist[v] = JSON.parse(to_addressHistory[v]);
    }
    this.setData({ list: to_addresslist })
    var that = this;
    if (options.f == "c") {
      that.setData({
        maptype:"c"
      })
    }
    wx.getSystemInfo({
      success: function (res) {
        var widthCtr = res.screenWidth;        //console.log(widthCtr + "=====");
        that.setData({
          height: res.windowHeight - 59,
          controls: [{
            id: 1,
            iconPath: '../../images/cur.png',
            position: {
              left: res.screenWidth - 50,
              top: res.windowHeight - 100,
              width: 30,
              height: 30
            },
            clickable: true
          }]
        })
      }
    });
    this.getCurrent();
  },
  //获取标记点的位置
  getpointLatLog: function (e){
    if(e.type == 'end')
      this.getLngLat();
  },
  getCity: function (lat,lng,iscity=false){
    var that = this;
    util.NetRequest({
      showLoading:false,
      url: api.getCity,
      data: { latitude: lat, longitude: lng },
      success: function (res) {
        if (res.result.ad_info.city){
          if (iscity===true){
            //wx.setStorageSync("currentCity", res.result.ad_info.city);
            wx.setStorageSync("currentCity", "杭州市");//限制当前城市 杭州市
          }
          if(that.data.maptype == "c"){
            //选择当前地址
            var selectedFromPlant = { 
              lat: lat, 
              lng: lng, 
              departure: res.result.formatted_addresses.recommend, 
              address: res.result.address,
              title: res.result.formatted_addresses.recommend,
              fight_id: 0
            };
            wx.setStorageSync("selectedFromPlant", JSON.stringify(selectedFromPlant));
          } else if (that.data.maptype == "f"){
            //选择目的地地址
          }
          that.setData({ startPoint: res.result.formatted_addresses.recommend })
          that.setData({ startlng: res.result.location.lng })
          that.setData({ startlat: res.result.location.lat })
          console.log(res.result);
        }else{
          util.common.showTipError("城市获取失败");
        }
      }
    })
  },
  getCurrent:function (){
    var that = this;
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success: function (res) {
        that.setData({ lat: res.latitude });
        that.setData({ lng: res.longitude });
        that.getCity(res.latitude, res.longitude, true);
      }
    })
  },
  controltap:function(e){
    var that = this; 
    wx.getLocation({ 
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度      
      success: function (res) {        
        var latitude = res.latitude        
        var longitude = res.longitude        
        that.setData({          
          lat: latitude,//纬度           
          lng: longitude,//经度                   
        })      
      }    
    })
  },
  //获取中间点的经纬度，并mark出来
  getLngLat: function () {
    var that = this;
    this.mapCtx = wx.createMapContext("myMapCCCC");
    this.mapCtx.getCenterLocation({
      success: function (res) {
        that.getCity(res.latitude, res.longitude)
      }
    })
  },
  bindReplaceInput:function (e){
    var that = this;
    var keywords = e.detail.value;
    var city = wx.getStorageSync("currentCity");
    wx.request({
      url: api.searchPoint,
      data: { code: keywords, city: city},
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        if(res.data.status==0)
          that.setData({list:res.data.data});
      },
      fail: function (res) {
        console.log(res)
      },
      complete:function(res){
        console.log(res)
      }
    }),
    this.setData({
      sectionlistTrue: false
    })
  },
  changeMaker: function (e){    
    var lat = e.currentTarget.dataset.lat;
    var lng = e.currentTarget.dataset.lng;
    var address = e.currentTarget.dataset.address;
    var title = e.currentTarget.dataset.title;
    
    var markers = [];
    var marker = {
      latitude: lat,
      longitude: lng,
    };
    wx.setStorageSync("selectedAddress", JSON.stringify({ lat: lat, lng: lng, address: title }) );
    markers.push(marker);
    //记住历史地址
    var to_addressHistoryItem = JSON.stringify({location:{lat: lat, lng: lng}, address: address, title: title });
    var to_addressHistory = wx.getStorageSync("to_addressHistory") == "" ? [] : wx.getStorageSync("to_addressHistory");
    //判断记录是否大于指定数量,大于则删除最后一条添加
    if (to_addressHistory.length > 20) {
      to_addressHistory.pop();
      to_addressHistory.unshift(to_addressHistoryItem);
    } else {
      to_addressHistory.unshift(to_addressHistoryItem);
    }
    //去除重复记录
    var to_addressHistory_new = [];
    for (var i = 0; i < to_addressHistory.length; i++) {
      if (to_addressHistory.indexOf(to_addressHistory[i]) == i) {
        to_addressHistory_new.push(to_addressHistory[i]);
      }
    }
    wx.setStorageSync("to_addressHistory", to_addressHistory_new);
    //创建选择的点
    this.setData({
      showList: false,
      markers: markers,
      lng: lng,
      lat: lat,
      maptop:"0rpx",
      sectionlistTrue: true
    })
  },
  checkAddress: function (){
    var selectedFromPlant=wx.getStorageSync("selectedFromPlant");
    // var lat = this.data.startlat;
    // var lng = this.data.startlng;
    // var address = this.data.startPoint;
    // console.log(selectedFromPlant);
    //记住历史地址
    var addressHistoryItem = selectedFromPlant;
    var addressHistory = wx.getStorageSync("addressHistory") == "" ? [] : wx.getStorageSync("addressHistory");
    var isadd=1
    for (var i = 0; i < addressHistory.length; i++) 
    {
      if (addressHistory[i] == addressHistoryItem) 
      {
        isadd=0;
      }
    }
    if (isadd == 1)
    {
      if (addressHistory.length >=3) {
        addressHistory.pop();
        addressHistory.unshift(addressHistoryItem);
      } else {
        addressHistory.unshift(addressHistoryItem);
      }
    }
    //去除重复记录
    // var addressHistory_new = [];
    // for (var i = 0; i < addressHistory.length; i++) {
    //   if (addressHistory.indexOf(addressHistory[i]) == i) {
    //     addressHistory_new.push(addressHistory[i]);
    //   }
    // }
    wx.setStorageSync("addressHistory", addressHistory);
    wx.navigateBack()
  },
  historyLocation: function (e) {
    var index = e.currentTarget.dataset.index;
    var list = wx.getStorageSync("addressHistory");
    var select_item=JSON.parse(list[index]);
    console.log(select_item.lng);
    this.setData({
      lat: select_item.lat,//纬度           
      lng: select_item.lng,//经度                   
    }) 
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },
  onReady:function(){
    //this.getLngLat();
  }
})